package com.example.springboot.mqtt.task;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springboot.mqtt.entity.LotterySsq;
import com.example.springboot.mqtt.entity.Prizegrades;
import com.example.springboot.mqtt.serivice.ILotterySsqService;
import com.example.springboot.mqtt.serivice.IPrizegradesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@Slf4j
public class lottery {
    @Autowired
    private ILotterySsqService lotterySsqService;
    @Autowired
    private IPrizegradesService prizegradesService;

    /**
     * 双色球
     * 每周日、二、四 21:20 爬取最新数据
     */
//    @Scheduled(cron = "0 20,30 21,22 ? * 0,2,4")
    public void getSsq(){
        String url = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=3&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=30&week=&systemType=PC";
        String jsonStr = HttpRequest.get(url)
                .header(Header.COOKIE, getCookie())
                .header(Header.REFERER, "https://www.cwl.gov.cn/ygkj/wqkjgg/ssq/")
                .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .execute().body();
        JSON body = JSONUtil.parse(jsonStr);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        try {
            if (jsonObject.get("state").equals(0)) {
                Object result = jsonObject.get("result");
                JSONArray resultArray = JSONUtil.parseArray(result);
                for (Object lottery : resultArray) {
                    log.info("双色球：{}", lottery);
                    JSONObject lotteryObject = JSONUtil.parseObj(lottery);
                    LotterySsq lotterySsq = JSONUtil.toBean(lotteryObject, LotterySsq.class);

                    LambdaQueryWrapper<LotterySsq> lotterySsqQuery = new LambdaQueryWrapper<>();
                    lotterySsqQuery.eq(LotterySsq::getCode, lotterySsq.getCode());
                    LotterySsq lot = lotterySsqService.getOne(lotterySsqQuery);
                    if (lot != null) {
                        lotterySsqService.update(lotterySsq, lotterySsqQuery);
                    } else {
                        lotterySsqService.save(lotterySsq);
                    }

                    Object prizegradesObject = lotteryObject.get("prizegrades");
                    JSONArray prizegradesArray = JSONUtil.parseArray(prizegradesObject);
                    List<Prizegrades> prizegrades = JSONUtil.toList(prizegradesArray, Prizegrades.class);
                    log.info("双色球奖品：{}", prizegrades);
                    for (Prizegrades prizegrade : prizegrades) {
                        prizegrade.setLotteryId(lotterySsq.getCode());
                        prizegrade.setType(prizegrade.getType());
                        LambdaQueryWrapper<Prizegrades> prizegradeQuery = new LambdaQueryWrapper<>();
                        prizegradeQuery.eq(Prizegrades::getLotteryId, prizegrade.getLotteryId()).eq(Prizegrades::getType, prizegrade.getType());
                        Prizegrades prize = prizegradesService.getOne(prizegradeQuery);
                        if (prize != null) {
                            prizegradesService.update(prizegrade, prizegradeQuery);
                        } else {
                            prizegradesService.save(prizegrade);
                        }
                    }
                }
            }else{
                log.info("双色球：{}", jsonObject);
            }
        }catch (Exception e) {
            log.error("双色球爬取失败：{}", jsonObject);
            e.printStackTrace();
        }
    }

    private String getCookie(){
        String url = "https://www.cwl.gov.cn/ygkj/wqkjgg/ssq/";
        return HttpRequest.get(url)
               .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
               .execute().header(Header.COOKIE);
    }
}
